import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:heytea_kit/toast.dart';
import 'package:url_launcher/url_launcher.dart';

enum MapApp {
  Apple,
  Amap,
  Baidu,
  Tencent,
}

class MapUtils {
  static String nameOfMapApp(MapApp app) {
    switch (app) {
      case MapApp.Apple:
        return 'Apple 地图';
      case MapApp.Amap:
        return '高德地图';
      case MapApp.Baidu:
        return '百度地图';
      case MapApp.Tencent:
        return '腾讯地图';
    }
    return null;
  }

  static Future<void> navigateTo(
    BuildContext context,
    double latitude,
    double longitude,
  ) {
    return showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        final appList = MapApp.values.toList();
        if (!Platform.isIOS && !Platform.isMacOS) {
          appList.remove(MapApp.Apple);
        }

        return ListView.builder(
          shrinkWrap: true,
          itemCount: appList.length,
          itemBuilder: (BuildContext context, int index) {
            final app = appList[index];
            final appName = nameOfMapApp(app);
            return ListTile(
              title: Text(appName),
              onTap: () async {
                Navigator.of(context).pop();
                final url = toUrl(app, latitude, longitude);
                if (url != null && await canLaunch(url)) {
                  await launch(url);
                } else {
                  HeyTeaToast.showFailure('未检测到$appName~');
                }
              },
            );
          },
        );
      },
    );
  }

  static String toUrl(
    MapApp app,
    double latitude,
    double longitude,
  ) {
    switch (app) {
      case MapApp.Apple:
        return 'http://maps.apple.com/?&daddr=$latitude,$longitude';
      case MapApp.Amap:
        if (Platform.isIOS) {
          return 'iosamap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';
        } else if (Platform.isAndroid) {
          return 'androidamap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';
        }
        break;
      case MapApp.Baidu:
        return 'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';
      case MapApp.Tencent:
        return 'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';
    }

    return null;
  }
}
